package com.lsbc.pay.config;

import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * Spring Boot 2.0 解决跨域问题
 * 
 * @Author Evan
 *
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer,WebMvcRegistrations {
	
    
    /**
	 * 返回字符串带引号
	 * @return
	 */
	@Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }
	
	/**
	 * 字符串转换器放第一位
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.add(0, stringHttpMessageConverter());
	}

	@Bean
	@ConditionalOnMissingBean({ FastJsonHttpMessageConverter.class })
	public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		List<MediaType> mediaTypes = new ArrayList<>(4);
		
		mediaTypes.add(MediaType.parseMediaType("text/html;charset=UTF-8"));
		mediaTypes.add(MediaType.parseMediaType("text/plain;charset=UTF-8"));
		mediaTypes.add(MediaType.parseMediaType("application/json;charset=UTF-8"));
		mediaTypes.add(MediaType.parseMediaType("application/x-www-form-urlencoded"));
		
		converter.setSupportedMediaTypes(mediaTypes);
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);
		ValueFilter localDateTimeToLongValueFilter = (Object object, String name, Object value) -> {
			if (value != null) {
				if (value instanceof LocalDateTime) {
					return ((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
				}
			}
			return value;
		};
		fastJsonConfig.setSerializeFilters(localDateTimeToLongValueFilter);
		converter.setFastJsonConfig(fastJsonConfig);
		return converter;
	}
	
}
